package com.platform.qujia.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.platform.qujia.constantEnum.DecimalConstant;
import com.platform.qujia.pojo.Station;
import com.platform.qujia.service.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.platform.qujia.constantEnum.TianQuetechPayEnum;
import com.platform.qujia.dao.PayOrderMapper;
import com.platform.qujia.dao.ReductionRulesMapper;
import com.platform.qujia.pay.service.impl.TianQuetechPay;
import com.platform.qujia.pojo.PayOrder;
import com.platform.qujia.pojo.TradePaymentRecordsDO;
import com.platform.qujia.pojo.TradeReverseScanPayNotifyDO;

@Service
public class NotifyServiceImlp implements NotifyService {

	private static Logger logger =(Logger) LoggerFactory.getLogger(NotifyServiceImlp.class);
	
	@Lazy
	@Autowired 
	private TradePaymentRecordsService tradePaymentRecordsService;
	@Autowired
	private PayOrderMapper payOrderMapper;
	@Autowired
	private ReductionActivityService reductionActivityService;
	@Autowired
	private EnterpriseService enterpriseService;
	
	@Override
	public JSONObject tradeReverse(HttpServletRequest request, HttpServletResponse response) {
		//TODO 需要校验订单、校验回调信息
		logger.info("天阙随心付回调-回调信息");
		JSONObject resultJson = new JSONObject();
		TradeReverseScanPayNotifyDO notifydo=new TradeReverseScanPayNotifyDO();
		String recvInfo=null;
		try {
			recvInfo = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
		} catch (IOException e) {
			e.printStackTrace();
		}
		logger.info("recvInfo:"+recvInfo);
		logger.info("---------------------------------------");
		resultJson.put("code","FAIL");
        resultJson.put("msg","失败");
		if(StringUtils.isEmpty(recvInfo)) {
			logger.info("天阙随心付回调-对象映射为空");
			return resultJson;
		}
		notifydo = JSON.parseObject(recvInfo, TradeReverseScanPayNotifyDO.class);
		logger.info("notifydo:"+notifydo.toString());
		if(tradePaymentRecordsService.updateTradePaymentRecords(notifydo)==0) {
			logger.info("订单号:"+notifydo.getOrdNo()+"|支付订单更新失败");
			return resultJson;
		}
//		TradePaymentRecordsDO recordsDO=tradePaymentRecordsService.selectOneOrdNo(notifydo.getOrdNo());
//		if(recordsDO!=null) {
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			Date paydate=null;
			try {
				paydate = format.parse(notifydo.getPayTime());
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
			int type=updateTradeReverseOrder(notifydo.getOrdNo(),paydate);
			if(type==0) {
				logger.info("订单号:"+notifydo.getOrdNo()+"|业务订单更新失败");
			}
//		}else {
//			logger.info("支付订单未找到");
//		}
        resultJson.put("code","success");
        resultJson.put("msg","成功");
		return resultJson;

	}
	
	/**
	 * 更新订单
	 * @param orderSn
	 * @param payDate
	 * @return
	 */
	public int updateTradeReverseOrder(String orderSn,Date payDate) {
		PayOrder order=payOrderMapper.selectByOrdNo(orderSn);
		if(order==null) {
			logger.info("订单记录不存在，不进行更新");
			return 0;
		}
//		BigDecimal serviceCharge=order.getServiceCharge();
//		BigDecimal commission=serviceCharge.divide(new BigDecimal(1000)).multiply(new BigDecimal(order.getAmt())).setScale(2,BigDecimal.ROUND_UP);
//		BigDecimal receivedAmt= new BigDecimal(order.getAmt()).subtract(commission);
		PayOrder payOrder=new PayOrder();
    	payOrder.setOrderNo(order.getOrderNo());
    	payOrder.setStatus(TianQuetechPayEnum.PAY_SUCCESS.getValue().toString());
		payOrder.setPayDate(payDate);
		BigDecimal orderAmt = BigDecimal.valueOf(order.getAmt());
		payOrder.setActualAmt(orderAmt);
		Station station = enterpriseService.selectStationById(order.getStationId());
		if (StringUtils.equals("0",order.getChannelFeePayer())) {
			// 司机承担渠道费
			if (station != null && station.getIsShowSaasAmtCommission() == 0) {
				// 后台订单列表不展示渠道费
				BigDecimal recAmt = order.getReceivableAmt() == null ? BigDecimal.ZERO : BigDecimal.valueOf(order.getReceivableAmt());
				BigDecimal disAmt = order.getDiscountAmt() == null ? BigDecimal.ZERO : BigDecimal.valueOf(order.getDiscountAmt());
				BigDecimal couAmt = order.getDiscountCouponAmt() == null ? BigDecimal.ZERO : BigDecimal.valueOf(order.getDiscountCouponAmt());
				BigDecimal amt = recAmt.subtract(disAmt).subtract(couAmt);
				if (amt.compareTo(BigDecimal.ZERO)<=0) {
					amt = DecimalConstant.O_01;
				}
				payOrder.setAmt(amt.doubleValue());
			}
		}
//    	payOrder.setServiceCharge(serviceCharge);
//    	payOrder.setCommission(commission.doubleValue());
//    	payOrder.setReceivedAmt(receivedAmt.doubleValue());
    	//更新订单支付时间
//    	payOrderMapper.updateOrderPayDate(payDate, orderSn);
    	//扣除活动预算
    	if(order.getActivityId()!=null) {
    		reductionActivityService.updateReductionActivityBudget(BigDecimal.valueOf(order.getDiscountAmt()).negate(),order.getActivityId().intValue());
    	}
    	return payOrderMapper.updatePayOrder(payOrder);
    }
	
}
